"""
python文件 - 百度翻译
"""
import requests
import execjs
import re

class BdSpider:
    def __init__(self):
        self.post_url = 'https://fanyi.baidu.com/v2transapi?from=fra&to=zh'
        self.post_headers = {
            '''Accept''': '''*/*''',
            '''Accept-Encoding''': '''gzip, deflate, br''',
            '''Accept-Language''': '''zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6''',
            '''Cache-Control''': '''no-cache''',
            '''Connection''': '''keep-alive''',
            '''Content-Length''': '''137''',
            '''Content-Type''': '''application/x-www-form-urlencoded; charset=UTF-8''',
            '''Cookie''': '''BIDUPSID=67C30C1D069DFF1967C0D055E566A18F; PSTM=1586240617; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; __yjs_duid=1_8343fd16fa3aede957c0350eb06829031618365140546; MCITY=-131%3A; BAIDUID=C2C5468E8B1D1E31AA79C723A78B3B3B:FG=1; BDSFRCVID_BFESS=3-COJexroG0YhwbedlRT5TQNEeKKvV3TDYLtOwXPsp3LGJLVgfLiEG0Pt_NNY_L-abvWogKK0mOTHv-F_2uxOjjg8UtVJeC6EG0Ptf8g0M5; H_BDCLCKID_SF_BFESS=JJAO_IKMtCvDqTrP-trf5DCShUFsJKrmB2Q-XPoO3KJZj-3PbtOS0l303bQw04QiW5cpoMbgylRM8P3y0bb2DUA1y4vpK-5r2mTxoUJ2XhrFof7sqtQD5l-ebPRiJPr9QgbqslQ7tt5W8ncFbT7l5hKpbt-q0x-jLTnhVn0MBCK0HPonHj8aej3y3J; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; BAIDU_WISE_UID=wapp_1625469181311_904; BAIDUID_BFESS=60920D01293B23C32E774486949E8E8B:FG=1; H_PS_PSSID=34099_34224_34228_34004_34107_34134_26350_34237; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1625731051,1625797161; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1625797198; __yjs_st=2_MWU4NTViZWQzMDJjOWEwZjljYmZkZmUzNGY2NzlhMGZjMGFlYzYxOWVjMWI0N2I4OTAyOGVjNWM2N2Y4YzYwZjIyZDFkYTgxZjFkMzMwNzAxZTNjODNkZjg3MTE0MzI5NzdjOGMyMDg5OWNmZGQwYzYwYjg4MWUwZmQ4MjMzMjA5M2M2NjMwMDBlMWRiNDYxZmZiNjc2ZmMxZWIxN2FkYzY4OTFlNzhlMWM1ZjMwY2ViODRjZDE2M2YxZDVjYjE3MmMzZDNiZTk5MjljZTU4OWY3Njc1MDYzYjg2N2VlNzY1YTBmM2ZiNDc0MGM3NzIwNzY4ZmJjZjNjMGNkYTU3N183X2RiYTA1NjQ5; ab_sr=1.0.1_NWM4MzUyYWUwOGRlZTk0YTM3NWYyYzY5OGY1OTFhZjAzMTMyYjEwYmFmNGY5MDNlZjEzNDhlMzEyODRkOGViZDk4ZWVhNWFhZTljZGI4YzZiYzQ1YzAyNGJiYjgzMjFkMDYxOGM5ZWU2ZjVhZTg5Yzc3NTE4Y2JiMjcxMmUxZjZhNTEzYjliMDMwODUwMTU2NGFiNTZkZjMzMzUwYmFlNg==''',
            '''Host''': '''fanyi.baidu.com''',
            '''Origin''': '''https://fanyi.baidu.com''',
            '''Pragma''': '''no-cache''',
            '''Referer''': '''https://fanyi.baidu.com/''',
            '''sec-ch-ua''': '''"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"''',
            '''sec-ch-ua-mobile''': '''?0''',
            '''Sec-Fetch-Dest''': '''empty''',
            '''Sec-Fetch-Mode''': '''cors''',
            '''Sec-Fetch-Site''': '''same-origin''',
            '''User-Agent''': '''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36''',
            '''X-Requested-With''': '''XMLHttpRequest''',
        }
        self.word = input('Input word:')
        # get请求获取gtk、token
        self.get_url = 'https://fanyi.baidu.com/'
        # F12抓取翻译主页get请求的请求头
        self.get_headers = {
            '''Accept''': '''text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9''',
            '''Accept-Encoding''': '''gzip, deflate, br''',
            '''Accept-Language''': '''zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6''',
            '''Cache-Control''': '''no-cache''',
            '''Connection''': '''keep-alive''',
            '''Cookie''': '''BIDUPSID=67C30C1D069DFF1967C0D055E566A18F; PSTM=1586240617; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; __yjs_duid=1_8343fd16fa3aede957c0350eb06829031618365140546; MCITY=-131%3A; BAIDUID=C2C5468E8B1D1E31AA79C723A78B3B3B:FG=1; BDSFRCVID_BFESS=3-COJexroG0YhwbedlRT5TQNEeKKvV3TDYLtOwXPsp3LGJLVgfLiEG0Pt_NNY_L-abvWogKK0mOTHv-F_2uxOjjg8UtVJeC6EG0Ptf8g0M5; H_BDCLCKID_SF_BFESS=JJAO_IKMtCvDqTrP-trf5DCShUFsJKrmB2Q-XPoO3KJZj-3PbtOS0l303bQw04QiW5cpoMbgylRM8P3y0bb2DUA1y4vpK-5r2mTxoUJ2XhrFof7sqtQD5l-ebPRiJPr9QgbqslQ7tt5W8ncFbT7l5hKpbt-q0x-jLTnhVn0MBCK0HPonHj8aej3y3J; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; BAIDU_WISE_UID=wapp_1625469181311_904; BAIDUID_BFESS=60920D01293B23C32E774486949E8E8B:FG=1; H_PS_PSSID=34099_34224_34228_34004_34107_34134_26350_34237; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1625731051,1625797161; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1625801609; __yjs_st=2_MWU4NTViZWQzMDJjOWEwZjljYmZkZmUzNGY2NzlhMGZjMGFlYzYxOWVjMWI0N2I4OTAyOGVjNWM2N2Y4YzYwZjIyZDFkYTgxZjFkMzMwNzAxZTNjODNkZjg3MTE0MzI5NzdjOGMyMDg5OWNmZGQwYzYwYjg4MWUwZmQ4MjMzMjA5M2M2NjMwMDBlMWRiNDYxZmZiNjc2ZmMxZWIxN2FkYzY4OTFlNzhlMWM1ZjMwY2ViODRjZDE2M2YxZDVjYjE3NWUwYzE1OWZiYzNlZmMxOTIyZDU2MjRkNGE5YTlmYjMzNDZiNTZmYWRiZWI0M2VjNTIxYWRhZjAxZDVhZWIwZl83XzVmMzNmOGE0; ab_sr=1.0.1_ZWY0YWEwOTZlYzUzNDNmZWYzNGQ5YTZhM2U1NjhlNjkxNmE5NWQ2ODQ4ZTYxYTM4NTgyOWZjMzM2MzMxMDU5NzkzYWIzNTFlY2U3NDBhMjA2NWEyNGZmZjA2MjAxYzE5ZGM3ZTlkNWMwMmZiYmNkYTQxMmU5ODYyNzk2NGFjYTEyYTgxNWU0ODRiNDNlNjY0ZjhlODI1MjM2ODJkODU2YQ==''',
            '''Host''': '''fanyi.baidu.com''',
            '''Pragma''': '''no-cache''',
            '''sec-ch-ua''': '''"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"''',
            '''sec-ch-ua-mobile''': '''?0''',
            '''Sec-Fetch-Dest''': '''document''',
            '''Sec-Fetch-Mode''': '''navigate''',
            '''Sec-Fetch-Site''': '''none''',
            '''Sec-Fetch-User''': '''?1''',
            '''Upgrade-Insecure-Requests''': '''1''',
            '''User-Agent''': '''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36''',
        }

    def get_sign(self):
        """利用execjs模块获取sign"""
        with open('translate.js', 'r') as f:
            jscode = f.read()
        # 获取gtk
        gtk, token = self.get_gtk_token()
        # 执行js代码
        jsobj = execjs.compile(jscode)
        sign = jsobj.eval('e("{}","{}")'.format(self.word, gtk))

        return sign

    def get_gtk_token(self):
        """获取gtk和token"""
        html = requests.get(url=self.get_url, headers=self.get_headers).text
        gtk_list = re.findall("window.gtk = '(.*?)'", html, re.S)
        token_list = re.findall("token: '(.*?)'", html, re.S)
        if gtk_list and token_list:
            gtk, token = gtk_list[0], token_list[0]
            return gtk, token
        print('gtk or token failed')

    def attack_bd(self):
        # 获取sign
        sign = self.get_sign()
        # 获取token
        gtk, token = self.get_gtk_token()
        data = {
            '''from''': '''en''',
            '''to''': '''zh''',
            '''query''': self.word,
            '''transtype''': '''realtime''',
            '''simple_means_flag''': '''3''',
            '''sign''': sign,
            '''token''': token,
            '''domain''': '''common''',
        }
        html = requests.post(url=self.post_url, data=data, headers=self.post_headers).json()
        result = html['trans_result']['data'][0]['dst']
        print(result)

if __name__ == '__main__':
    spider = BdSpider()
    spider.attack_bd()














